package com.example.demo.service.impl;

import cn.hutool.core.io.FileUtil;
import com.example.demo.entity.BdRecords;
import com.example.demo.service.RecordsService;
import com.google.common.collect.Maps;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Map;

@Service
public class RecordsServiceImpl implements RecordsService {
    @Value("${file.path}")
    private String filePath;
    public void exportToPdf(BdRecords bdRecords, HttpServletResponse response) throws DocumentException, IOException {
        Map<String, Object> paramsa =Maps.newHashMap();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        paramsa.put("name", bdRecords.getName());
        paramsa.put("date", sdf.format(bdRecords.getDate()));
        paramsa.put("area", bdRecords.getArea());
        paramsa.put("groundProtection1", bdRecords.getGroundProtection1());
        paramsa.put("groundProtection2", bdRecords.getGroundProtection2());
        paramsa.put("groundProtection3", bdRecords.getGroundProtection3());
        paramsa.put("groundProtection4", bdRecords.getGroundProtection4());
        paramsa.put("groundProtection5", bdRecords.getGroundProtection5());
        paramsa.put("groundProtection6", bdRecords.getGroundProtection6());
        paramsa.put("groundProtectionNotes", bdRecords.getGroundProtectionNotes());
        paramsa.put("decorationProtection1", bdRecords.getDecorationProtection1());
        paramsa.put("decorationProtection2", bdRecords.getDecorationProtection2());
        paramsa.put("decorationProtection3", bdRecords.getDecorationProtection3());
        paramsa.put("decorationProtection4", bdRecords.getDecorationProtection4());
        paramsa.put("decorationProtection5", bdRecords.getDecorationProtection5());
        paramsa.put("decorationProtection6", bdRecords.getDecorationProtection6());
        paramsa.put("decorationProtection7", bdRecords.getDecorationProtection7());
        paramsa.put("decorationProtection8", bdRecords.getDecorationProtection8());
        paramsa.put("decorationProtectionNotes", bdRecords.getDecorationProtectionNotes());
        paramsa.put("pollutionControl1", bdRecords.getPollutionControl1());
        paramsa.put("pollutionControl2", bdRecords.getPollutionControl2());
        paramsa.put("pollutionControl3", bdRecords.getPollutionControl3());
        paramsa.put("pollutionControl4", bdRecords.getPollutionControl4());
        paramsa.put("pollutionControl5", bdRecords.getPollutionControl5());
        paramsa.put("pollutionControl6", bdRecords.getPollutionControl6());
        paramsa.put("pollutionControl7", bdRecords.getPollutionControl7());
        paramsa.put("pollutionControl8", bdRecords.getPollutionControl8());
        paramsa.put("pollutionControlNotes", bdRecords.getPollutionControlNotes());
        paramsa.put("constructionWork1", bdRecords.getConstructionWork1());
        paramsa.put("constructionWork2", bdRecords.getConstructionWork2());
        paramsa.put("constructionWork3", bdRecords.getConstructionWork3());
        paramsa.put("constructionWork4", bdRecords.getConstructionWork4());
        paramsa.put("constructionWork5", bdRecords.getConstructionWork5());
        paramsa.put("constructionWork6", bdRecords.getConstructionWork6());
        paramsa.put("constructionWork7", bdRecords.getConstructionWork7());
        paramsa.put("constructionWorkNotes", bdRecords.getConstructionWorkNotes());
        paramsa.put("electrificationWork1", bdRecords.getElectrificationWork1());
        paramsa.put("electrificationWork2", bdRecords.getElectrificationWork2());
        paramsa.put("electrificationWork3", bdRecords.getElectrificationWork3());
        paramsa.put("electrificationWork4", bdRecords.getElectrificationWork4());
        paramsa.put("electrificationWork5", bdRecords.getElectrificationWork5());
        paramsa.put("electrificationWork6", bdRecords.getElectrificationWork6());
        paramsa.put("electrificationWork7", bdRecords.getElectrificationWork7());
        paramsa.put("electrificationWorkNotes", bdRecords.getElectrificationWorkNotes());
        paramsa.put("otherWork1", bdRecords.getOtherWork1());
        paramsa.put("otherWork2", bdRecords.getOtherWork2());
        paramsa.put("otherWork3", bdRecords.getOtherWork3());
        paramsa.put("otherWork4", bdRecords.getOtherWork4());
        paramsa.put("otherWork5", bdRecords.getOtherWork5());
        paramsa.put("otherWork6", bdRecords.getOtherWork6());
        paramsa.put("otherWorkNotes", bdRecords.getOtherWorkNotes());
        paramsa.put("otherProblems", bdRecords.getOtherProblems());
        paramsa.put("pollution1", bdRecords.getPollution1());
        paramsa.put("pollution2", bdRecords.getPollution2());
        paramsa.put("pollution3", bdRecords.getPollution3());
        paramsa.put("pollution4", bdRecords.getPollution4());
        paramsa.put("pollution5", bdRecords.getPollution5());
        paramsa.put("pollution6", bdRecords.getPollution6());
        paramsa.put("pollutionNotes", bdRecords.getPollutionNotes());

        // 利用模板生成pdf
        String templatePath = filePath+"recordsTemplate.pdf";

        // 生成的新文件路径
        String fileName = "巡检单"+ bdRecords.getName()+".pdf";
        String newPDFPath = "D:\\system\\system-back\\files\\pdf\\" + fileName;
        PdfReader reader;
        FileOutputStream out;
        ByteArrayOutputStream bos;
        PdfStamper stamper;
        try {
            out = new FileOutputStream(newPDFPath);// 输出流
            reader = new PdfReader(templatePath);// 读取pdf模板
            bos = new ByteArrayOutputStream();
            stamper = new PdfStamper(reader, bos);
            AcroFields form = stamper.getAcroFields();

            for (String key : paramsa.keySet()) {
                if (paramsa.get(key)==null){
                    paramsa.put(key,"");
                }
                form.setField(key,paramsa.get(key).toString(),true);
            }
            stamper.setFormFlattening(true);// 如果为false那么生成的PDF文件还能编辑，一定要设为true
            stamper.close();
            Document doc = new Document();
            PdfCopy copy = new PdfCopy(doc, out);
            copy.open();
            doc.open();
            //生成多页pdf
            PdfImportedPage importPage=null;
            for (int i=1;i<=reader.getNumberOfPages();i++){
                importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), i);
                copy.addPage(importPage);
            }
            copy.close();
            doc.close();
            out.close();
        } catch (IOException | DocumentException e) {
            throw new RuntimeException(e);
        }

        try {
            OutputStream os;  // 新建一个输出流对象
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            response.setContentType("application/octet-stream");
            byte[] bytes = FileUtil.readBytes(newPDFPath);  // 通过文件的路径读取文件字节流
            os = response.getOutputStream();   // 通过输出流返回文件
            os.write(bytes);
            os.flush();
            os.close();
        } catch (Exception e) {
            System.out.println("文件下载失败");
        }
    }

}
